package org.firestorm.traficforecast.test;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class ReadXML {
	public static void main(String[] args) {
		File xmlFile = new File("E:\\HOC TAP\\KI 20141\\Project\\WorkSpace\\map.osm");
		DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder;
		try {
			dBuilder = dbfactory.newDocumentBuilder();
		    org.w3c.dom.Document doc = dBuilder.parse(xmlFile);
//		    NodeList nodeLists = doc.getElementsByTagName("way");
//		    int len = nodeLists.getLength();
//		    for(int i = 0; i< len; i++){
//		    	Node nNode = nodeLists.item(i);
//		        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
//
//		            Element eElement = (Element) nNode;
//		            	NodeList tagList = eElement.getElementsByTagName("nd");
//		            	System.out.println(tagList.getLength());
//		        }
//		    }
//		    System.out.println(nodeLists.getLength());
		    NodeList nodeLists = doc.getElementsByTagName("node");
		    System.out.println(nodeLists.getLength());
		    boolean check = true;
		    int count = 0;
		    while(check){
		    	Node node = nodeLists.item(0);
		    	if(node != null){
		    		node.getParentNode().removeChild(node);
//		    		System.out.println(count++);
		    		count += 1;
		    	}else{
		    		check = false;
		    	}
		    }
		    System.out.println(count);
		    writeXML(doc);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void writeXML(org.w3c.dom.Document doc){
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer;
		try {
			transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File("E:\\HOC TAP\\KI 20141\\Project\\WorkSpace\\way1.osm"));
			
			transformer.transform(source, result);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}
}
